package com.home.admin.index;

import com.home.admin.config.WebClientConfig;
import com.home.common.constants.shiro.ShiroConstant;
import com.home.common.utils.string.StringUtils;
import com.home.security.browser.shiro.AuthToken;
import com.home.security.core.enums.AppClientEnum;
import com.home.webapp.vo.LoginVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Description: 登录入口
 * Created by 王大宸 on 2020-09-28 20:43
 * Created with IntelliJ IDEA.
 */
@Controller
@CrossOrigin
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private WebClientConfig webClientConfig;

    /***
     * 功能说明：跳转到登录页面,删除之前的用户认证信息
     *
     * @author 王大宸
     * @date 2020/10/8 16:48
     * @param response response
     * @return java.lang.String
     */
    @GetMapping(value = "/login")
    public String login(HttpServletResponse response, String msg, ModelMap modelMap) {
        //假如要删除名称为JSESSIONID的Cookie
        Cookie newCookie = new Cookie("JSESSIONID", null);
        //立即删除型
        newCookie.setMaxAge(0);
        //项目所有目录均有效，这句很关键，否则不敢保证删除
        newCookie.setPath("/");
        //重新写入，将覆盖之前的
        response.addCookie(newCookie);

        modelMap.put("msg", msg);

        modelMap.put("copyrightYear", webClientConfig.getCopyrightYear());
        modelMap.put("clientName", webClientConfig.getName());
        modelMap.put("version", webClientConfig.getVersion());
        modelMap.put("issuer", webClientConfig.getIssuer());
        return ShiroConstant.LOGIN_URL;
    }

    /***
     * 功能说明：登录
     *
     * @author 王大宸
     * @date 2020/10/8 16:50  @RequestBody @Valid
     * @param loginVo loginVo  ServerResponse<String>
     * @return com.home.common.framework.msg.ServerResponse<java.lang.String>
     */
    @PostMapping(value = "/account/token")
    public String accountToken(LoginVo loginVo) throws UnsupportedEncodingException {
        Subject subject = SecurityUtils.getSubject();
        String msg = "";
        if (null == loginVo) {
            msg = "7";
            msg = URLEncoder.encode(msg, "utf8");
            return "redirect:/login?msg=" + msg;
        }
        if (StringUtils.isEmpty(loginVo.getPassword())) {
            msg = "5";
            msg = URLEncoder.encode(msg, "utf8");
            return "redirect:/login?msg=" + msg;
        }
        if (StringUtils.isEmpty(loginVo.getUsername())) {
            msg = "6";
            msg = URLEncoder.encode(msg, "utf8");
            return "redirect:/login?msg=" + msg;
        }
        try {
            AuthToken token = new AuthToken(loginVo.getUsername(), loginVo.getPassword(), AppClientEnum.WEB_APP.getClientCode());
            subject.login(token);
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            msg = "1";
            //  msg = "用户信息不存在, 请检查账号是否正确!";
        } catch (IncorrectCredentialsException e) {
            //  msg = "登录密码错误, 请检查密码是否正确！";
            msg = "2";
        } catch (LockedAccountException e) {
            //   msg = "账号已被冻结, 请联系管理人员！";
            msg = "3";
        } catch (Exception e) {
            logger.error("登录失败: ", e);
            msg = "0";
        }
        msg = URLEncoder.encode(msg, "utf8");
        return "redirect:/login?msg=" + msg;
    }

}
